package com.tbit.uqbike.client.controller;

import com.tbit.uqbike.client.common.ResultMsg;
import com.tbit.uqbike.client.constant.CommonConstant;
import com.tbit.uqbike.client.constant.DepositStateConstant;
import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.dao.core.UserAuthWhiteListDao;
import com.tbit.uqbike.client.dto.WhiteListCheckResultDTO;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.StudentAuth;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.pojo.UserAuthWhiteList;
import com.tbit.uqbike.client.service.StudentAuthService;
import com.tbit.uqbike.client.service.TokenService;
import com.tbit.uqbike.client.service.UserService;
import com.tbit.uqbike.client.util.Assert;
import com.tbit.uqbike.client.util.DateTimeUtil;
import com.tbit.uqbike.client.util.OutputUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 学生身份认证
 *
 * @author chen
 * @date 2022/05/13
 */
@Controller
@RequestMapping("/studentAuth")
public class StudentAuthController {
    @Autowired
    private UserService userService;
    @Autowired
    private StudentAuthService studentAuthService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private StudentAuthController itself;


    /**
     * 获取学生认证申请信息
     *
     * @param token    令牌
     * @param response 响应
     * @param session  会话
     * @ignoreParams request
     */
    @RequestMapping("/getApply")
    public void queryPage(String token, HttpServletRequest request, HttpServletResponse response,
                          HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        try {
            User user = tokenService.getUser(token);
            StudentAuth studentAuth = studentAuthService.getStatus(user.getUserId());
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, studentAuth);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }


    /**
     * 申请学生认证
     *
     * @param imageFiles 图像文件
     * @param token      令牌
     * @param name       名字
     * @param studentNO  学生编号
     * @param reason     申请理由
     * @param response   响应
     * @param session    会话
     * @ignoreParams request
     */
    @RequestMapping("/apply")
    public void apply(@RequestParam(value = "imageFiles",required = false) MultipartFile[] imageFiles, String token, String name, String studentNO, String reason,
                      HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        try {
            User user = tokenService.getUser(token);

            /**校验*/
            Assert.notNull(user, "-10002", "用户不存在");
            Assert.hasLength(studentNO, "-4002", "学号不能为空");

            WhiteListCheckResultDTO checkWhiteList = studentAuthService.checkWhiteList(token, studentNO);
            if (!checkWhiteList.isInWhiteList()){
                if(Objects.isNull(imageFiles) || imageFiles.length == 0){
                    throw new BaseException("-4002", "非白名单用户认证图片不能为空");
                }
            }
            //用户如果已经提交过学生认证审核，并且状态是未审核或审核通过，则不能再进行提交
            StudentAuth haveStudentAuth = studentAuthService.getStatus(user.getUserId());
            if (Objects.nonNull(haveStudentAuth) && (Objects.equals(haveStudentAuth.getCheckState(), CommonConstant.STUDENT_AUTH_CHECK_STATUS_SUBMIT)
                    || Objects.equals(haveStudentAuth.getCheckState(),CommonConstant.STUDENT_AUTH_CHECK_STATUS_AGREE))){
                throw new BaseException("-3045", "已经提交过学生认证审核，请勿重复提交");
            }

            /**判断用户是否已经提交押金*/
            /*User userDB = userService.getByUserId(user.getUserId());
            if (userDB.getDepositState() == DepositStateConstant.DEPOSIT_STATE_PAY) {
                throw new BaseException("-3045", "请先退押金再申请学生认证免押金");
            }*/

            StudentAuth studentAuth = new StudentAuth();
            studentAuth.setName(name);
            studentAuth.setReason(reason);
            studentAuth.setStudentNO(studentNO);
            studentAuth.setUserId(user.getUserId());
            studentAuth.setAccountId(user.getAccountId());
            studentAuth.setCreateTime(DateTimeUtil.getNowTime());
            studentAuth.setCheckState(0);
            String result = studentAuthService.insert(studentAuth, imageFiles, request);

            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, result);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 申请学生认证-无图片
     *
     * 兼容前端无图片请求 apply 接口报错  the request was rejected because no multipart boundary was found
     * @param token    令牌
     * @param name 名字
     * @param studentNO  学生编号
     * @param reason 申请理由
     */
    @RequestMapping("/normalApply")
    public void normalApply(String token, String name, String studentNO, String reason,HttpServletRequest request, HttpServletResponse response){
       itself.apply(null, token, name, studentNO, reason, request, response, null);
    }

    /**
     * 校验 AuthNo 是否在白名单
     *
     * @param token    令牌
     * @param authNo 认证编号
     * @return 白名单校验结果
     */
    @Validated
    @ResponseBody
    @GetMapping("/checkWhiteList")
    public ResultMsg<WhiteListCheckResultDTO> checkWhiteList(@NotBlank String token,@NotBlank String authNo) {
        WhiteListCheckResultDTO result = studentAuthService.checkWhiteList(token, authNo);
        return ResultMsg.success(result);
    }

}
